<template>
  <div class="login">
    <div :class="['content',(toggle?'s--signup':'')]">
      <div class="form sign-in">
        <h2>欢迎回来</h2>
        <a-form id="formLogin" ref="loginForm" class="user-layout-login" :model="loginForm">
          <a-form-item style="text-align:center">
            <p class="title_wenzi">帐号</p>
            <a-input
              v-model="loginForm.username"
              v-decorator="[
                'username',
                {rules: [{ required: true, message: '请输入帐户名或邮箱地址' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
              ]"
              size="large"
              type="text"
              style="width: 50%;"
              placeholder="账户: admin"
            >
              <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-item>
          <a-form-item style="text-align:center">
            <p class="title_wenzi">密码</p>
            <a-input
              v-model="loginForm.password"
              v-decorator="[
                'password',
                {rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}
              ]"
              size="large"
              type="password"
              autocomplete="false"
              style="width: 50%;"
              placeholder="密码: admin or ant.design"
            >
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
          </a-form-item>
          <a-form-item style="text-align:center">
            <p class="title_wenzi">验证码</p>
            <a-input
              v-model="loginForm.code"
              size="large"
              autocomplete="false"
              placeholder="验证码"
              style="width: 50%;"
            >
              <a-icon slot="prefix" type="code" :style="{ color: 'rgba(0,0,0,.25)' }" />
            </a-input>
            <div class="login-code">
              <span
                v-if="code.type == 'text'"
                class="login-code-img"
                @click="refreshCode"
              >{{ code.value }}</span>
              <img v-else :src="code.src" class="login-code-img" @click="refreshCode" />
            </div>
          </a-form-item>
        </a-form>
        <p class="forgot-pass">
          <a href="javascript:">忘记密码？</a>
        </p>
        <button type="button" class="submit" @click="handleLogin">登 录</button>
      </div>
      <div class="sub-cont">
        <div class="img">
          <div class="img__text m--up">
            <h2>还未注册？</h2>
            <p>立即注册，发现大量机会！</p>
          </div>
          <div class="img__text m--in">
            <h2>已有帐号？</h2>
            <p>有帐号就登录吧，好久不见了！</p>
          </div>
          <div class="img__btn" @click="toggles">
            <span class="m--up">注 册</span>
            <span class="m--in">登 录</span>
          </div>
        </div>
        <div class="form sign-up">
          <h2>立即注册</h2>
          <a-form id="formLogin" ref="loginForm" class="user-layout-login" :model="loginForm">
            <a-form-item style="text-align:center">
              <p class="title_wenzi">用户名</p>
              <a-input v-model="loginForm.username" size="large" type="text" style="width: 50%;">
                <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input>
            </a-form-item>
            <a-form-item style="text-align:center">
              <p class="title_wenzi">邮箱</p>
              <a-input
                v-model="loginForm.username"
                v-decorator="[
                'username',
                {rules: [{ required: true, message: '请输入帐户名或邮箱地址' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}
              ]"
                size="large"
                type="text"
                style="width: 50%;"
                placeholder="账户: admin"
              >
                <a-icon slot="prefix" type="user" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input>
            </a-form-item>
            <a-form-item style="text-align:center">
              <p class="title_wenzi">密码</p>
              <a-input
                v-model="loginForm.password"
                v-decorator="[
                'password',
                {rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}
              ]"
                size="large"
                type="password"
                autocomplete="false"
                style="width: 50%;"
                placeholder="密码: admin or ant.design"
              >
                <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(0,0,0,.25)' }" />
              </a-input>
            </a-form-item>
          </a-form>
          <button type="button" class="submit">注 册</button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import md5 from "js-md5";
import TwoStepCaptcha from "@/components/tools/TwoStepCaptcha";
import { mapActions } from "vuex";
import { timeFix, randomLenNum } from "@/utils/util";
import { getSmsCaptcha, get2step } from "@/api/login";
export default {
  data() {
    return {
      toggle: false,
      loginErroMsg: "",
      customActiveKey: "tab1",
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      // form: this.$form.createForm(this),
      form: "",
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      },
      baseUrl: "http://admin.huajianmo.com",
    //   baseUrl: process.env.VUE_APP_API_ADMIN_URL,
      loginForm: {
        username: "flyray-mall",
        password: "1qaz.lo9",
        code: "",
        redomStr: ""
      },
      code: {
        src:"http://admin.huajianmo.com/code?randomStr=" + randomLenNum(4, true),
        // src: process.env.VUE_APP_API_ADMIN_URL+'/code?randomStr=' + randomLenNum(4, true),
        value: "",
        len: 4,
        type: "image"
      },
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    }
  },
  created() {
    console.log(process);
    this.$store.commit("SET_TOKEN");
    // get2step({ })
    //   .then(res => {
    //     this.requiredTwoStepCaptcha = res.result.stepCode
    //   })
    //   .catch(() => {
    //     this.requiredTwoStepCaptcha = false
    //   })
    // // this.requiredTwoStepCaptcha = true
    this.refreshCode();
  },
  methods: {
    ...mapActions(["Login", "Logout"]),
    toggles() {
      this.toggle = !this.toggle;
    },
    refreshCode() {
      window.console.log(1);
      this.loginForm.code = "";
      this.loginForm.randomStr = randomLenNum(this.code.len, true);
      this.code.type === "text"
        ? (this.code.value = randomLenNum(this.code.len))
        : (this.code.src =
            this.baseUrl + `/code?randomStr=${this.loginForm.randomStr}`);
    },
    btn(){
        console.log(this.loginForm);
    },
    handleLogin() {
      console.log(this.loginForm);
      this.$store
        .dispatch("LoginByUsername", this.loginForm)
        .then(res => {
          console.log("login success");
          console.log(res);
          if (res.code == 1) {
            this.requestFailed(res);
            return;
          }
          if (res.access_token) {
            this.loginSuccess(res);
            this.$router.push({
              path: this.redirect || "/",
              query: this.otherQuery
            });
          } else {
            this.requestFailed("err");
          }
          windows.location.href = "";
        })
        .catch(() => {
          this.refreshCode();
        });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    // handler
    handleUsernameOrEmail(rule, value, callback) {
      const { state } = this;
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
      if (regex.test(value)) {
        state.loginType = 0;
      } else {
        state.loginType = 1;
      }
      callback();
    },
    handleTabClick(key) {
      this.customActiveKey = key;
      // this.form.resetFields()
    },
    handleSubmit(e) {
      e.preventDefault();
      const {
        form: { validateFields },
        state,
        customActiveKey,
        Login
      } = this;

      state.loginBtn = true;

      const validateFieldsKey =
        customActiveKey === "tab1"
          ? ["username", "password"]
          : ["mobile", "captcha"];

      validateFields(validateFieldsKey, { force: true }, (err, values) => {
        if (!err) {
          console.log("login form", values);
          const loginParams = { ...values };
          delete loginParams.username;
          loginParams[!state.loginType ? "email" : "username"] =
            values.username;
          loginParams.password = md5(values.password);
          Login(loginParams)
            .then(res => this.loginSuccess(res))
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.loginBtn = false;
            });
        } else {
          setTimeout(() => {
            state.loginBtn = false;
          }, 600);
        }
      });
    },
    getCaptcha(e) {
      e.preventDefault();
      const {
        form: { validateFields },
        state
      } = this;

      validateFields(["mobile"], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true;

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60;
              state.smsSendBtn = false;
              window.clearInterval(interval);
            }
          }, 1000);

          const hide = this.$message.loading("验证码发送中..", 0);
          getSmsCaptcha({ mobile: values.mobile })
            .then(res => {
              setTimeout(hide, 2500);
              this.$notification["success"]({
                message: "提示",
                description:
                  "验证码获取成功，您的验证码为：" + res.result.captcha,
                duration: 8
              });
            })
            .catch(err => {
              setTimeout(hide, 1);
              clearInterval(interval);
              state.time = 60;
              state.smsSendBtn = false;
              this.requestFailed(err);
            });
        }
      });
    },
    stepCaptchaSuccess() {
      this.loginSuccess();
    },
    stepCaptchaCancel() {
      this.Logout().then(() => {
        this.loginBtn = false;
        this.stepCaptchaVisible = false;
      });
    },
    loginSuccess(res) {
      console.log(res);
      // check res.homePage define, set $router.push name res.homePage
      // Why not enter onComplete
      /*
      this.$router.push({ name: 'analysis' }, () => {
        console.log('onComplete')
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      })
      */
      this.$router.push({ path: "/" });
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: "欢迎",
          description: `${timeFix()}，欢迎回来`
        });
      }, 1000);
      this.isLoginError = false;
    },
    requestFailed(err) {
      this.isLoginError = true;
      this.loginErroMsg = err.msg;
      this.$notification["error"]({
        message: "错误",
        description:
          ((err.msg || {}).data || {}).message || "请求出现错误，请稍后再试",
        duration: 4
      });
      this.refreshCode();
    }
  }
};
</script>
<style scoped  lang="scss">
.login {
  *,
  *:before,
  *:after {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
  }

  body {
    font-family: "Open Sans", Helvetica, Arial, sans-serif;
    background: #ededed;
  }

  input,
  button {
    border: none;
    outline: none;
    background: none;
    font-family: "Open Sans", Helvetica, Arial, sans-serif;
  }

  .tip {
    font-size: 20px;
    margin: 40px auto 50px;
    text-align: center;
  }

  .content {
    overflow: hidden;
    position: absolute;
    left: 50%;
    top: 50%;
    width: 900px;
    height: 550px;
    margin: -300px 0 0 -450px;
    background: #fff;
  }

  .form {
    position: relative;
    width: 640px;
    height: 100%;
    transition: -webkit-transform 0.6s ease-in-out;
    transition: transform 0.6s ease-in-out;
    transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out;
    padding: 50px 30px 0;
  }

  .sub-cont {
    overflow: hidden;
    position: absolute;
    left: 640px;
    top: 0;
    width: 900px;
    height: 100%;
    padding-left: 260px;
    background: #fff;
    transition: -webkit-transform 0.6s ease-in-out;
    transition: transform 0.6s ease-in-out;
    transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out;
  }

  .content.s--signup .sub-cont {
    -webkit-transform: translate3d(-640px, 0, 0);
    transform: translate3d(-640px, 0, 0);
  }

  button {
    display: block;
    margin: 0 auto;
    width: 260px;
    height: 36px;
    border-radius: 30px;
    color: #fff;
    font-size: 15px;
    cursor: pointer;
  }

  .img {
    overflow: hidden;
    z-index: 2;
    position: absolute;
    left: 0;
    top: 0;
    width: 260px;
    height: 100%;
    padding-top: 360px;
  }

  .img:before {
    content: "";
    position: absolute;
    right: 0;
    top: 0;
    width: 900px;
    height: 100%;
    background-image: url("../../assets/bg.jpg");
    background-size: cover;
    transition: -webkit-transform 0.6s ease-in-out;
    transition: transform 0.6s ease-in-out;
    transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out;
  }

  .img:after {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6);
  }

  .content.s--signup .img:before {
    -webkit-transform: translate3d(640px, 0, 0);
    transform: translate3d(640px, 0, 0);
  }

  .img__text {
    z-index: 2;
    position: absolute;
    left: 0;
    top: 50px;
    width: 100%;
    padding: 0 20px;
    text-align: center;
    color: #fff;
    transition: -webkit-transform 0.6s ease-in-out;
    transition: transform 0.6s ease-in-out;
    transition: transform 0.6s ease-in-out, -webkit-transform 0.6s ease-in-out;
  }

  .img__text h2 {
    margin-bottom: 10px;
    font-weight: normal;
  }

  .img__text p {
    font-size: 14px;
    line-height: 1.5;
  }

  .content.s--signup .img__text.m--up {
    -webkit-transform: translateX(520px);
    transform: translateX(520px);
  }
  .img__text.m--in {
    -webkit-transform: translateX(-520px);
    transform: translateX(-520px);
  }

  .content.s--signup .img__text.m--in {
    -webkit-transform: translateX(0);
    transform: translateX(0);
  }

  .img__btn {
    overflow: hidden;
    z-index: 2;
    position: relative;
    width: 100px;
    height: 36px;
    margin: 0 auto;
    background: transparent;
    color: #fff;
    text-transform: uppercase;
    font-size: 15px;
    cursor: pointer;
  }
  .img__btn:after {
    content: "";
    z-index: 2;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    border: 2px solid #fff;
    border-radius: 30px;
  }

  .img__btn span {
    position: absolute;
    left: 0;
    top: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    transition: -webkit-transform 0.6s;
    transition: transform 0.6s;
    transition: transform 0.6s, -webkit-transform 0.6s;
  }

  .img__btn span.m--in {
    -webkit-transform: translateY(-72px);
    transform: translateY(-72px);
  }

  .content.s--signup .img__btn span.m--in {
    -webkit-transform: translateY(0);
    transform: translateY(0);
  }

  .content.s--signup .img__btn span.m--up {
    -webkit-transform: translateY(72px);
    transform: translateY(72px);
  }

  h2 {
    width: 100%;
    font-size: 26px;
    text-align: center;
  }

  label {
    display: block;
    width: 260px;
    margin: 25px auto 0;
    text-align: center;
  }

  #formLogin {
    .title_wenzi {
      font-size: 12px;
      color: #909399;
      text-transform: uppercase;
    }
  }
  input {
    display: block;
    width: 100%;
    margin-top: 5px;
    padding-bottom: 5px;
    font-size: 16px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.4);
    text-align: center;
  }

  .forgot-pass {
    margin-top: 15px;
    text-align: center;
    font-size: 12px;
    color: #cfcfcf;
  }

  .forgot-pass a {
    color: #cfcfcf;
  }

  .submit {
    margin-top: 40px;
    margin-bottom: 20px;
    background: #d4af7a;
    text-transform: uppercase;
  }

  .fb-btn {
    border: 2px solid #d3dae9;
    color: #8fa1c7;
  }
  .fb-btn span {
    font-weight: bold;
    color: #455a81;
  }

  .sign-in {
    transition-timing-function: ease-out;
  }
  .content.s--signup .sign-in {
    transition-timing-function: ease-in-out;
    transition-duration: 0.6s;
    -webkit-transform: translate3d(640px, 0, 0);
    transform: translate3d(640px, 0, 0);
  }

  .sign-up {
    -webkit-transform: translate3d(-900px, 0, 0);
    transform: translate3d(-900px, 0, 0);
  }
  .content.s--signup .sign-up {
    -webkit-transform: translate3d(0, 0, 0);
    transform: translate3d(0, 0, 0);
  }
}
</style>
